using CollabApp.Application.DTOs.Game;
using CollabApp.Application.Interfaces;
using CollabApp.Domain.Entities.Game;
using CollabApp.Domain.Services;
using CollabApp.Domain.ValueObjects;
using Microsoft.Extensions.Logging;
using System.Collections.Concurrent;
using System.Text.Json;

namespace CollabApp.Application.Services.Game
{
    /// <summary>
    /// 画线圈地游戏服务实现
    /// </summary>
    public class LineDrawingGameService : CollabApp.Application.Interfaces.ILineDrawingGameService
    {
        private readonly IRedisService _redisService;
        private readonly ILogger<LineDrawingGameService> _logger;
        private readonly CollabApp.Domain.Services.ILineDrawingGameLogicService _domainGameService;
        
        // 游戏状态缓存
        private readonly ConcurrentDictionary<Guid, LineDrawingGameState> _gameStates = new();
        private readonly ConcurrentDictionary<string, DateTime> _lastActionTime = new();

        // 常量配置
        private const double MAX_PATH_LENGTH_RATIO = 1.5; // 最大画线长度为地图对角线的1.5倍
        private const int MIN_ACTION_INTERVAL_MS = 16; // 最小操作间隔16毫秒（约60fps）
        private const double BASE_MOVEMENT_SPEED = 200.0; // 基础移动速度：每秒200像素

        public LineDrawingGameService(
            IRedisService redisService,
            ILogger<LineDrawingGameService> logger,
            Domain.Services.ILineDrawingGameLogicService domainGameService)
        {
            _redisService = redisService;
            _logger = logger;
            _domainGameService = domainGameService;
        }

        /// <summary>
        /// 处理玩家移动 - 实现持续移动和自动画线机制
        /// 根据游戏规则：出生后首次按键开始移动，移动中可以改变方向但不会停止
        /// </summary>
        public async Task<LineDrawingMoveResult> ProcessPlayerMoveAsync(Guid gameId, Guid playerId, Position newPosition, long timestamp)
        {
            try
            {
                // 验证操作频率
                if (!ValidateActionRate(playerId, timestamp))
                {
                    return new LineDrawingMoveResult
                    {
                        Success = false,
                        Errors = { "操作过于频繁" },
                        Timestamp = timestamp
                    };
                }

                // 获取游戏状态
                var gameState = await GetGameStateAsync(gameId);
                if (gameState == null || gameState.Status != "playing")
                {
                    return new LineDrawingMoveResult
                    {
                        Success = false,
                        Errors = { "游戏状态无效" },
                        Timestamp = timestamp
                    };
                }

                // 获取玩家状态
                var player = gameState.Players.FirstOrDefault(p => p.PlayerId == playerId);
                
                _logger.LogInformation("移动请求 - PlayerId: {PlayerId}, 找到玩家: {Found}, 游戏中玩家总数: {PlayerCount}", 
                    playerId, player != null, gameState.Players.Count);
                    
                if (gameState.Players.Any())
                {
                    _logger.LogInformation("游戏中的玩家ID列表: {PlayerIds}", 
                        string.Join(", ", gameState.Players.Select(p => p.PlayerId.ToString())));
                }
                
                if (player == null || !player.IsAlive)
                {
                    _logger.LogWarning("玩家状态无效 - PlayerId: {PlayerId}, 玩家存在: {PlayerExists}, 玩家存活: {IsAlive}", 
                        playerId, player != null, player?.IsAlive ?? false);
                        
                    return new LineDrawingMoveResult
                    {
                        Success = false,
                        Errors = { "玩家状态无效" },
                        Timestamp = timestamp
                    };
                }

                // 检查是否在无敌期间
                if (player.InvincibilityEndTime.HasValue && DateTime.UtcNow < player.InvincibilityEndTime)
                {
                    _logger.LogInformation("玩家 {PlayerId} 在无敌期间移动", playerId);
                }

                // 验证移动合法性（圆形地图边界检查）
                var moveValidation = await ValidateCircularMapMovement(gameId, playerId, newPosition);
                if (!moveValidation.IsValid)
                {
                    return new LineDrawingMoveResult
                    {
                        Success = false,
                        Errors = { moveValidation.ErrorMessage ?? "移动无效" },
                        Timestamp = timestamp
                    };
                }

                // 更新玩家位置
                var previousPosition = player.CurrentPosition;
                player.CurrentPosition = newPosition;
                
                // 根据游戏规则：玩家移动时自动画线（从出生点或己方领地开始）
                // 如果玩家尚未开始画线，检查是否可以开始
                if (!player.IsDrawing)
                {
                    var drawingTerritoryInfo = CheckPlayerTerritoryStatus(player, newPosition, gameState.Players);
                    // 修复画线条件：离开安全区和自己的领地时开始画线
                    if (!drawingTerritoryInfo.IsInOwnTerritory && !drawingTerritoryInfo.IsInSafeZone)
                    {
                        // 自动开始画线
                        player.IsDrawing = true;
                        player.CurrentPath = new List<Position> { previousPosition, newPosition };
                        player.CurrentPathLength = previousPosition.DistanceTo(newPosition);
                        
                        _logger.LogInformation("玩家 {PlayerId} 离开安全区域，自动开始画线", playerId);
                    }
                }
                else
                {
                    // 继续画线，添加路径点
                    player.CurrentPath.Add(newPosition);
                    
                    // 画线长度限制 - 单次画线不能超过地图对角线的1.5倍
                    var pathLength = CalculatePathLength(player.CurrentPath);
                    var mapDiagonal = Math.Sqrt(Math.Pow(gameState.MapWidth, 2) + Math.Pow(gameState.MapHeight, 2));
                    var maxLength = mapDiagonal * MAX_PATH_LENGTH_RATIO;
                    
                    player.CurrentPathLength = pathLength;
                    
                    _logger.LogInformation("玩家 {PlayerId} 轨迹点添加 - 总点数: {PathCount}, 当前位置: ({X},{Y})", 
                        playerId, player.CurrentPath.Count, newPosition.X, newPosition.Y);
                    
                    // 检查是否回到安全区域，如果是则完成画线
                    var currentTerritoryInfo = CheckPlayerTerritoryStatus(player, newPosition, gameState.Players);
                    if (currentTerritoryInfo.IsInOwnTerritory || currentTerritoryInfo.IsInSafeZone)
                    {
                        _logger.LogInformation("玩家 {PlayerId} 回到安全区域，完成画线 - 轨迹长度: {PathLength}", playerId, player.CurrentPath.Count);
                        // 这里应该调用完成画线的逻辑，但暂时继续现有逻辑
                    }
                    
                    if (pathLength > maxLength)
                    {
                        // 路径过长，强制死亡
                        _logger.LogWarning("玩家 {PlayerId} 画线长度超限：{PathLength}/{MaxLength}", playerId, pathLength, maxLength);
                        await ProcessPlayerDeathAsync(gameId, playerId, null, "画线过长", timestamp);
                        return new LineDrawingMoveResult
                        {
                            Success = false,
                            Errors = { "画线长度超限，玩家死亡" },
                            Timestamp = timestamp
                        };
                    }
                    
                    // 检查轨迹碰撞（移除自撞死亡规则）
                    var collisionResult = await CheckTrailCollisionAsync(gameId, playerId, previousPosition, newPosition);
                    if (collisionResult.HasCollision && !player.IsGhost)
                    {
                        // 跳过自撞，只处理其他类型的碰撞
                        if (collisionResult.CollisionType != "self_trail")
                        {
                            var deathReason = collisionResult.CollisionType switch
                            {
                                "player_trail" => "被截断",
                                "boundary" => "撞到边界",
                                _ => "轨迹碰撞"
                            };
                            
                            await ProcessPlayerDeathAsync(gameId, playerId, collisionResult.CollidedWithPlayerId, deathReason, timestamp);
                            return new LineDrawingMoveResult
                            {
                                Success = false,
                                Errors = { $"{deathReason}，玩家死亡" },
                                Timestamp = timestamp
                            };
                        }
                        else
                        {
                            // 自撞情况：记录但不死亡
                            _logger.LogInformation("玩家 {PlayerId} 自撞轨迹，继续游戏", playerId);
                        }
                    }
                }

                // 检查玩家领地状态（统一检查避免重复调用）
                var territoryInfo = CheckPlayerTerritoryStatus(player, newPosition, gameState.Players);
                
                // 更新威胁检测
                await UpdateThreatDetection(player, gameState.Players);

                // 保存状态
                await SaveGameStateAsync(gameId, gameState);

                return new LineDrawingMoveResult
                {
                    Success = true,
                    NewPosition = newPosition,
                    MovementSpeed = CalculateEffectiveMovementSpeed(player, territoryInfo),
                    IsInEnemyTerritory = territoryInfo.IsInEnemyTerritory,
                    CanStartDrawing = !player.IsDrawing && (territoryInfo.IsInOwnTerritory || territoryInfo.IsInSafeZone),
                    Timestamp = timestamp
                };
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, "处理玩家移动时发生错误: GameId={GameId}, PlayerId={PlayerId}", gameId, playerId);
                return new LineDrawingMoveResult
                {
                    Success = false,
                    Errors = { "系统错误" },
                    Timestamp = timestamp
                };
            }
        }

        /// <summary>
        /// 开始画线
        /// </summary>
        public async Task<LineDrawingResult> StartDrawingAsync(Guid gameId, Guid playerId, Position startPosition, long timestamp)
        {
            try
            {
                var gameState = await GetGameStateAsync(gameId);
                var player = gameState?.Players.FirstOrDefault(p => p.PlayerId == playerId);
                
                if (gameState == null || player == null || !player.IsAlive)
                {
                    return new LineDrawingResult
                    {
                        Success = false,
                        Errors = { "无效的游戏或玩家状态" },
                        Timestamp = timestamp
                    };
                }

                // 检查是否已在画线
                if (player.IsDrawing)
                {
                    return new LineDrawingResult
                    {
                        Success = false,
                        Errors = { "已在画线中" },
                        Timestamp = timestamp
                    };
                }

                // 检查是否在己方领地边缘或安全区域
                if (!CanStartDrawingAt(player, startPosition))
                {
                    return new LineDrawingResult
                    {
                        Success = false,
                        Errors = { "只能从己方领地或安全区域开始画线" },
                        Timestamp = timestamp
                    };
                }

                // 开始画线
                player.IsDrawing = true;
                player.CurrentPath = new List<Position> { startPosition };
                player.CurrentPosition = startPosition;

                await SaveGameStateAsync(gameId, gameState);

                return new LineDrawingResult
                {
                    Success = true,
                    IsDrawing = true,
                    CurrentPath = player.CurrentPath.ToList(),
                    PathLength = 0,
                    Timestamp = timestamp
                };
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, "开始画线时发生错误: GameId={GameId}, PlayerId={PlayerId}", gameId, playerId);
                return new LineDrawingResult
                {
                    Success = false,
                    Errors = { "系统错误" },
                    Timestamp = timestamp
                };
            }
        }

        /// <summary>
        /// 添加画线路径点
        /// </summary>
        public async Task<LineDrawingResult> AddPathPointAsync(Guid gameId, Guid playerId, Position pathPoint, long timestamp)
        {
            try
            {
                var gameState = await GetGameStateAsync(gameId);
                var player = gameState?.Players.FirstOrDefault(p => p.PlayerId == playerId);
                
                if (gameState == null || player == null || !player.IsAlive || !player.IsDrawing)
                {
                    return new LineDrawingResult
                    {
                        Success = false,
                        Errors = { "无效的画线状态" },
                        Timestamp = timestamp
                    };
                }

                // 检查碰撞
                var collisionResult = await CheckCollisionAsync(gameId, playerId, new List<Position> { player.CurrentPosition, pathPoint });
                if (collisionResult.HasCollision && collisionResult.ShouldDie)
                {
                    // 玩家死亡
                    await ProcessPlayerDeathAsync(gameId, playerId, collisionResult.CollidedWithPlayerId, 
                        collisionResult.CollisionType ?? "碰撞", timestamp);
                    
                    return new LineDrawingResult
                    {
                        Success = false,
                        CollisionDetected = true,
                        CollidedWithPlayerId = collisionResult.CollidedWithPlayerId,
                        Errors = { "发生碰撞，玩家死亡" },
                        Timestamp = timestamp
                    };
                }

                // 添加路径点
                player.CurrentPath.Add(pathPoint);
                player.CurrentPosition = pathPoint;

                var pathLength = CalculatePathLength(player.CurrentPath);
                await SaveGameStateAsync(gameId, gameState);

                return new LineDrawingResult
                {
                    Success = true,
                    IsDrawing = true,
                    CurrentPath = player.CurrentPath.ToList(),
                    PathLength = pathLength,
                    Timestamp = timestamp
                };
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, "添加路径点时发生错误: GameId={GameId}, PlayerId={PlayerId}", gameId, playerId);
                return new LineDrawingResult
                {
                    Success = false,
                    Errors = { "系统错误" },
                    Timestamp = timestamp
                };
            }
        }

        /// <summary>
        /// 完成圈地（路径闭合） - 实现领地面积实时计算并更新排名
        /// 采用高效的多边形面积算法，处理领地"吞噬"逻辑
        /// </summary>
        public async Task<TerritoryClaimResult> CompleteDrawingAsync(Guid gameId, Guid playerId, Position endPosition, long timestamp)
        {
            try
            {
                var gameState = await GetGameStateAsync(gameId);
                var player = gameState?.Players.FirstOrDefault(p => p.PlayerId == playerId);
                
                if (gameState == null || player == null || !player.IsAlive || !player.IsDrawing)
                {
                    return new TerritoryClaimResult
                    {
                        Success = false,
                        Errors = { "无效的画线状态" },
                        Timestamp = timestamp
                    };
                }

                // 检查是否可以在指定位置完成圈地
                if (!CanCompleteDrawingAt(player, endPosition, gameState.Players))
                {
                    return new TerritoryClaimResult
                    {
                        Success = false,
                        Errors = { "必须回到己方领地边缘或起点附近才能完成圈地" },
                        Timestamp = timestamp
                    };
                }

                // 完成路径（如果需要闭合）
                var completePath = player.CurrentPath.ToList();
                if (!completePath.Last().Equals(endPosition))
                {
                    completePath.Add(endPosition);
                }
                
                // 确保路径闭合
                if (completePath.Count >= 3 && !completePath.First().Equals(completePath.Last()))
                {
                    completePath.Add(completePath.First());
                }

                if (completePath.Count < 4) // 至少需要3个不同的点形成多边形
                {
                    player.IsDrawing = false;
                    player.CurrentPath.Clear();
                    player.CurrentPathLength = 0;
                    await SaveGameStateAsync(gameId, gameState);
                    
                    return new TerritoryClaimResult
                    {
                        Success = false,
                        Errors = { "圈地路径过短，无法形成有效区域" },
                        Timestamp = timestamp
                    };
                }

                // 创建新领地并计算面积（使用高效的多边形面积算法）
                var newTerritory = new Territory(completePath);
                var newTerritoryArea = newTerritory.Area;

                // 检查新领地是否有效（面积不能太小）
                const double MIN_TERRITORY_AREA = 100; // 最小领地面积
                if (newTerritoryArea < MIN_TERRITORY_AREA)
                {
                    player.IsDrawing = false;
                    player.CurrentPath.Clear();
                    player.CurrentPathLength = 0;
                    await SaveGameStateAsync(gameId, gameState);
                    
                    return new TerritoryClaimResult
                    {
                        Success = false,
                        Errors = { "圈地面积过小，无效圈地" },
                        Timestamp = timestamp
                    };
                }

                // 处理领地"吞噬"逻辑
                var engulfedTerritories = new List<Territory>();
                var engulfedArea = 0.0;
                var engulfedPlayers = new List<Guid>();

                // 检查是否吞噬了其他玩家的领地
                foreach (var otherPlayer in gameState.Players.Where(p => p.PlayerId != playerId))
                {
                    var territoriesBeforeEngulf = otherPlayer.Territories.ToList();
                    var engulfedByThisPlayer = new List<Territory>();

                    foreach (var territory in territoriesBeforeEngulf)
                    {
                        if (newTerritory.IsCompletelyEngulfed(territory))
                        {
                            engulfedByThisPlayer.Add(territory);
                            engulfedTerritories.Add(territory);
                            engulfedArea += territory.Area;
                            
                            // 从被吞噬玩家那里移除领地
                            otherPlayer.Territories.Remove(territory);
                            otherPlayer.TotalTerritoryArea -= territory.Area;
                        }
                    }

                    if (engulfedByThisPlayer.Any())
                    {
                        engulfedPlayers.Add(otherPlayer.PlayerId);
                        _logger.LogInformation("玩家 {PlayerId} 吞噬了玩家 {VictimId} 的 {Count} 块领地，面积: {Area}",
                            playerId, otherPlayer.PlayerId, engulfedByThisPlayer.Count, engulfedByThisPlayer.Sum(t => t.Area));
                    }
                }

                // 更新当前玩家状态
                player.IsDrawing = false;
                player.CurrentPath.Clear();
                player.CurrentPathLength = 0;
                
                // 添加新领地
                player.Territories.Add(newTerritory);
                
                // 实时计算并更新总领地面积
                var totalTerritoryArea = player.Territories.Sum(t => t.Area);
                player.TotalTerritoryArea = totalTerritoryArea;
                
                // 更新最大领地面积记录
                if (totalTerritoryArea > player.MaxTerritoryArea)
                {
                    player.MaxTerritoryArea = totalTerritoryArea;
                    _logger.LogInformation("玩家 {PlayerId} 创造了新的最大领地面积记录: {Area}", playerId, totalTerritoryArea);
                }

                // 重新计算排名（领地面积实时计算并更新排名）
                await UpdatePlayerRankings(gameState);
                await SaveGameStateAsync(gameId, gameState);

                var result = new TerritoryClaimResult
                {
                    Success = true,
                    NewTerritoryArea = newTerritoryArea,
                    TotalTerritoryArea = totalTerritoryArea,
                    EngulfedTerritories = engulfedTerritories,
                    EngulfedArea = engulfedArea,
                    NewRank = player.Rank,
                    Timestamp = timestamp
                };

                _logger.LogInformation("玩家 {PlayerId} 成功圈地: 新增面积={NewArea}, 总面积={TotalArea}, 吞噬面积={EngulfedArea}, 新排名={Rank}",
                    playerId, newTerritoryArea, totalTerritoryArea, engulfedArea, player.Rank);

                return result;
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, "完成圈地时发生错误: GameId={GameId}, PlayerId={PlayerId}", gameId, playerId);
                return new TerritoryClaimResult
                {
                    Success = false,
                    Errors = { "系统错误" },
                    Timestamp = timestamp
                };
            }
        }

        // 其他方法的简化实现...
        
        public async Task<CollisionCheckResult> CheckCollisionAsync(Guid gameId, Guid playerId, List<Position> currentPath)
        {
            var gameState = await GetGameStateAsync(gameId);
            if (gameState == null) return new CollisionCheckResult();

            var collisionResult = await _domainGameService.CheckPathCollision(playerId, currentPath, gameState);
            
            return new CollisionCheckResult
            {
                HasCollision = collisionResult.HasCollision,
                CollidedWithPlayerId = collisionResult.CollidedWithPlayerId,
                CollisionPoint = collisionResult.CollisionPoint,
                CollisionType = collisionResult.CollisionType,
                // 修改规则：只有碰到其他玩家的轨迹才会死亡，自撞不会死亡
                ShouldDie = collisionResult.HasCollision && collisionResult.CollisionType != "self_trail",
                CanAvoid = false // 暂时不支持避免碰撞
            };
        }

        public async Task<PowerUpPickupResult> PickupPowerUpAsync(Guid gameId, Guid playerId, Guid powerUpId, long timestamp)
        {
            try
            {
                var gameState = await GetGameStateAsync(gameId);
                if (gameState == null || gameState.Status != "playing")
                {
                    return new PowerUpPickupResult { Success = false, Errors = { "游戏状态无效" }, Timestamp = timestamp };
                }

                var player = gameState.Players.FirstOrDefault(p => p.PlayerId == playerId);
                if (player == null || !player.IsAlive)
                {
                    return new PowerUpPickupResult { Success = false, Errors = { "玩家状态无效" }, Timestamp = timestamp };
                }

                // 检查玩家是否已持有道具
                if (player.CurrentPowerUp.HasValue)
                {
                    return new PowerUpPickupResult { Success = false, Errors = { "已持有道具，无法拾取新道具" }, Timestamp = timestamp };
                }

                // 查找道具
                var powerUp = gameState.PowerUps.FirstOrDefault(p => p.Id == powerUpId && !p.IsCollected);
                if (powerUp == null)
                {
                    return new PowerUpPickupResult { Success = false, Errors = { "道具不存在或已被拾取" }, Timestamp = timestamp };
                }

                // 检查距离（玩家必须靠近道具才能拾取）
                var distance = player.CurrentPosition.DistanceTo(powerUp.Position);
                if (distance > 30) // 30像素范围内可拾取
                {
                    return new PowerUpPickupResult { Success = false, Errors = { "距离道具太远" }, Timestamp = timestamp };
                }

                // 拾取道具
                player.CurrentPowerUp = powerUp.Type;
                player.PowerUpExpireTime = DateTime.UtcNow.AddSeconds(GetPowerUpDuration(powerUp.Type));
                powerUp.IsCollected = true;

                await SaveGameStateAsync(gameId, gameState);

                return new PowerUpPickupResult
                {
                    Success = true,
                    PowerUpType = powerUp.Type,
                    PowerUpName = GetPowerUpName(powerUp.Type),
                    Description = GetPowerUpDescription(powerUp.Type),
                    Timestamp = timestamp
                };
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, "拾取道具时发生错误: GameId={GameId}, PlayerId={PlayerId}", gameId, playerId);
                return new PowerUpPickupResult { Success = false, Errors = { "系统错误" }, Timestamp = timestamp };
            }
        }

        public async Task<PowerUpUseResult> UsePowerUpAsync(Guid gameId, Guid playerId, PowerUpType powerUpType, long timestamp)
        {
            try
            {
                var gameState = await GetGameStateAsync(gameId);
                if (gameState == null || gameState.Status != "playing")
                {
                    return new PowerUpUseResult { Success = false, Errors = { "游戏状态无效" }, Timestamp = timestamp };
                }

                var player = gameState.Players.FirstOrDefault(p => p.PlayerId == playerId);
                if (player == null || !player.IsAlive)
                {
                    return new PowerUpUseResult { Success = false, Errors = { "玩家状态无效" }, Timestamp = timestamp };
                }

                // 检查玩家是否持有该道具
                if (player.CurrentPowerUp != powerUpType)
                {
                    return new PowerUpUseResult { Success = false, Errors = { "未持有该道具" }, Timestamp = timestamp };
                }

                // 应用道具效果
                var result = await _domainGameService.ApplyPowerUpEffect(playerId, new PowerUp(powerUpType, player.CurrentPosition, TimeSpan.Zero), gameState);

                if (result.Applied)
                {
                    // 根据道具类型应用具体效果
                    switch (powerUpType)
                    {
                        case PowerUpType.Lightning:
                            // 闪电效果已在移动验证中处理
                            player.PowerUpExpireTime = DateTime.UtcNow.AddMilliseconds(result.DurationMs);
                            break;

                        case PowerUpType.Shield:
                            // 护盾效果
                            player.HasShield = true;
                            player.PowerUpExpireTime = DateTime.UtcNow.AddMilliseconds(result.DurationMs);
                            break;

                        case PowerUpType.Bomb:
                            // 炸弹道具：创造领地
                            var bombTerritory = CreateCircularTerritory(player.CurrentPosition, 30);
                            player.Territories.Add(bombTerritory);
                            player.TotalTerritoryArea += bombTerritory.Area;
                            if (player.TotalTerritoryArea > player.MaxTerritoryArea)
                            {
                                player.MaxTerritoryArea = player.TotalTerritoryArea;
                            }
                            player.CurrentPowerUp = null; // 炸弹立即消耗
                            player.PowerUpExpireTime = null;
                            break;

                        case PowerUpType.Ghost:
                            // 幽灵效果
                            player.IsGhost = true;
                            player.PowerUpExpireTime = DateTime.UtcNow.AddMilliseconds(result.DurationMs);
                            break;
                    }

                    // 如果不是炸弹，清除道具
                    if (powerUpType != PowerUpType.Bomb)
                    {
                        player.CurrentPowerUp = null;
                    }

                    await UpdatePlayerRankings(gameState);
                    await SaveGameStateAsync(gameId, gameState);

                    return new PowerUpUseResult
                    {
                        Success = true,
                        UsedPowerUpType = powerUpType,
                        Effect = result.Effect,
                        DurationMs = result.DurationMs,
                        EffectParameters = result.Parameters,
                        Timestamp = timestamp
                    };
                }

                return new PowerUpUseResult { Success = false, Errors = { "道具使用失败" }, Timestamp = timestamp };
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, "使用道具时发生错误: GameId={GameId}, PlayerId={PlayerId}", gameId, playerId);
                return new PowerUpUseResult { Success = false, Errors = { "系统错误" }, Timestamp = timestamp };
            }
        }

        /// <summary>
        /// 处理玩家死亡 - 实现连续死亡惩罚机制
        /// 根据游戏规则：10秒内连续死亡2次以上，复活时间延长至8秒
        /// </summary>
        public async Task<PlayerDeathResult> ProcessPlayerDeathAsync(Guid gameId, Guid playerId, Guid? killerPlayerId, string deathReason, long timestamp)
        {
            try
            {
                var gameState = await GetGameStateAsync(gameId);
                var player = gameState?.Players.FirstOrDefault(p => p.PlayerId == playerId);
                
                if (gameState == null || player == null)
                {
                    return new PlayerDeathResult { Success = false, Errors = { "无效的玩家状态" } };
                }

                var currentTime = DateTime.UtcNow;

                // 检查连续死亡惩罚
                var respawnTimeMs = 5000; // 基础复活时间5秒
                
                if (player.LastDeathTime.HasValue && 
                    (currentTime - player.LastDeathTime.Value).TotalSeconds <= 10)
                {
                    // 10秒内的连续死亡
                    player.ConsecutiveDeaths++;
                    
                    if (player.ConsecutiveDeaths >= 2)
                    {
                        // 连续死亡2次以上，复活时间延长至8秒
                        respawnTimeMs = 8000;
                        _logger.LogInformation("玩家 {PlayerId} 连续死亡 {ConsecutiveDeaths} 次，复活时间延长", playerId, player.ConsecutiveDeaths);
                    }
                }
                else
                {
                    // 重置连续死亡计数
                    player.ConsecutiveDeaths = 1;
                }

                // 处理死亡
                player.IsAlive = false;
                player.IsDrawing = false;
                player.CurrentPath.Clear();
                player.CurrentPathLength = 0;
                player.DeathCount++;
                player.LastDeathTime = currentTime;
                player.IsUnderThreat = false;
                player.ThreatSourcePlayerId = null;
                
                // 清除道具效果
                player.CurrentPowerUp = null;
                player.PowerUpExpireTime = null;
                player.HasShield = false;
                player.IsGhost = false;
                
                // 保留20%最大领地面积作为"领地记忆"积分
                var remainingArea = player.MaxTerritoryArea * 0.2;
                player.TotalTerritoryArea = remainingArea;
                
                // 清除所有领地，只保留出生点安全区域
                player.Territories.Clear();
                var safeZoneTerritory = CreateCircularTerritory(player.SpawnPoint, 50);
                player.Territories.Add(safeZoneTerritory);

                // 增加击杀者计数
                if (killerPlayerId.HasValue)
                {
                    var killer = gameState.Players.FirstOrDefault(p => p.PlayerId == killerPlayerId.Value);
                    if (killer != null)
                    {
                        killer.KillCount++;
                        _logger.LogInformation("玩家 {KillerId} 击杀了 {PlayerId}，击杀数: {KillCount}", killerPlayerId.Value, playerId, killer.KillCount);
                    }
                }

                // 重新计算排名
                await UpdatePlayerRankings(gameState);
                await SaveGameStateAsync(gameId, gameState);

                return new PlayerDeathResult
                {
                    Success = true,
                    DeathReason = deathReason,
                    KillerPlayerId = killerPlayerId,
                    RemainingTerritoryArea = remainingArea,
                    RespawnTimeMs = respawnTimeMs,
                    HasDeathPenalty = player.ConsecutiveDeaths >= 2,
                    SpawnPoint = player.SpawnPoint,
                    Timestamp = timestamp
                };
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, "处理玩家死亡时发生错误: GameId={GameId}, PlayerId={PlayerId}", gameId, playerId);
                return new PlayerDeathResult { Success = false, Errors = { "系统错误" } };
            }
        }

        /// <summary>
        /// 处理玩家复活 - 实现无敌期机制
        /// 根据游戏规则：前3秒完全无敌，后2秒半无敌（可移动但免疫伤害）
        /// </summary>
        public async Task<PlayerRespawnResult> ProcessPlayerRespawnAsync(Guid gameId, Guid playerId, long timestamp)
        {
            try
            {
                var gameState = await GetGameStateAsync(gameId);
                var player = gameState?.Players.FirstOrDefault(p => p.PlayerId == playerId);
                
                if (gameState == null || player == null)
                {
                    return new PlayerRespawnResult { Success = false, Errors = { "无效的玩家状态" } };
                }

                var currentTime = DateTime.UtcNow;
                
                // 复活玩家
                player.IsAlive = true;
                player.CurrentPosition = player.SpawnPoint;
                player.RespawnTimestamp = timestamp;
                player.IsInSafeZone = true;
                
                // 设置无敌期：前3秒完全无敌，后2秒半无敌
                player.InvincibilityEndTime = currentTime.AddMilliseconds(5000); // 总计5秒无敌期
                
                // 清除道具和状态
                player.CurrentPowerUp = null;
                player.PowerUpExpireTime = null;
                player.HasShield = false;
                player.IsGhost = false;
                player.IsDrawing = false;
                player.CurrentPath.Clear();
                player.CurrentPathLength = 0;

                await SaveGameStateAsync(gameId, gameState);

                _logger.LogInformation("玩家 {PlayerId} 复活，无敌期至 {InvincibilityEnd}", playerId, player.InvincibilityEndTime);

                return new PlayerRespawnResult
                {
                    Success = true,
                    SpawnPosition = player.SpawnPoint,
                    IsInvincible = true,
                    InvincibilityTimeMs = 5000,
                    Timestamp = timestamp
                };
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, "处理玩家复活时发生错误: GameId={GameId}, PlayerId={PlayerId}", gameId, playerId);
                return new PlayerRespawnResult { Success = false, Errors = { "系统错误" } };
            }
        }

        public async Task<LineDrawingPlayerState?> GetPlayerStateAsync(Guid gameId, Guid playerId)
        {
            var gameState = await GetGameStateAsync(gameId);
            return gameState?.Players.FirstOrDefault(p => p.PlayerId == playerId);
        }

        /// <summary>
        /// 获取游戏状态快照
        /// </summary>
        /// <param name="gameId">游戏ID</param>
        /// <returns>游戏状态</returns>
        public async Task<LineDrawingGameState?> GetGameStateAsync(Guid gameId)
        {
            try
            {
                // 先从缓存获取
                if (_gameStates.TryGetValue(gameId, out var cachedState))
                {
                    return cachedState;
                }

                // 从Redis获取
                var stateJson = await _redisService.GetAsync<string>($"game_state:{gameId}");
                if (!string.IsNullOrEmpty(stateJson))
                {
                    var state = JsonSerializer.Deserialize<LineDrawingGameState>(stateJson);
                    if (state != null)
                    {
                        _gameStates.TryAdd(gameId, state);
                        return state;
                    }
                }

                return null;
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, "获取游戏状态时发生错误: GameId={GameId}", gameId);
                return null;
            }
        }

        public async Task<List<PlayerRankingDto>> GetRealTimeRankingAsync(Guid gameId)
        {
            _logger.LogInformation("=== 获取实时排行榜开始 === GameId: {GameId}", gameId);
            
            var gameState = await GetGameStateAsync(gameId);
            if (gameState == null) 
            {
                _logger.LogWarning("游戏状态为空，返回空排行榜 - GameId: {GameId}", gameId);
                return new List<PlayerRankingDto>();
            }

            _logger.LogInformation("获取到游戏状态，玩家数量: {PlayerCount}", gameState.Players?.Count ?? 0);
            
            if (gameState.Players?.Any() != true)
            {
                _logger.LogWarning("游戏状态中没有玩家，返回空排行榜 - GameId: {GameId}", gameId);
                return new List<PlayerRankingDto>();
            }

            var rankings = gameState.Players
                .OrderByDescending(p => p.TotalTerritoryArea)
                .Select((p, index) => new PlayerRankingDto
                {
                    PlayerId = p.PlayerId,
                    Username = p.Username,
                    Color = p.Color,
                    Rank = index + 1,
                    TerritoryArea = p.TotalTerritoryArea,
                    AreaPercentage = CalculateAreaPercentage(p.TotalTerritoryArea, gameState.MapWidth, gameState.MapHeight),
                    IsAlive = p.IsAlive,
                    KillCount = p.KillCount,
                    DeathCount = p.DeathCount,
                    KDRatio = p.DeathCount == 0 ? p.KillCount : (double)p.KillCount / p.DeathCount
                })
                .ToList();

            _logger.LogInformation("构建排行榜完成，排行榜条目数: {RankingCount}", rankings.Count);
            foreach (var ranking in rankings)
            {
                _logger.LogInformation("排行榜条目 - 排名: {Rank}, PlayerId: {PlayerId}, Username: {Username}, TerritoryArea: {TerritoryArea}, IsAlive: {IsAlive}",
                    ranking.Rank, ranking.PlayerId, ranking.Username, ranking.TerritoryArea, ranking.IsAlive);
            }

            return rankings;
        }

        /// <summary>
        /// 创建新游戏
        /// </summary>
        public async Task<GameCreationResult> CreateGameAsync(string roomCode, GameSettings settings, Guid hostPlayerId, string hostPlayerName)
        {
            try
            {
                var gameId = Guid.NewGuid();
                
                // 创建游戏状态
                var gameState = new LineDrawingGameState
                {
                    GameId = gameId,
                    RoomCode = roomCode,
                    Status = "waiting", // 等待玩家加入
                    CreatedAt = DateTime.UtcNow,
                    StartTime = null,
                    EndTime = null,
                    Duration = settings.Duration,
                    MapWidth = settings.MapWidth,
                    MapHeight = settings.MapHeight,
                    MaxPlayers = settings.MaxPlayers,
                    EnablePowerUps = settings.EnablePowerUps,
                    Players = new List<LineDrawingPlayerState>(),
                    PowerUps = new List<PowerUpState>()
                };

                // 添加房主玩家
                var hostPlayer = CreatePlayerState(hostPlayerId, hostPlayerName, gameState, isHost: true);
                gameState.Players.Add(hostPlayer);

                // 保存游戏状态
                await SaveGameStateAsync(gameId, gameState);
                
                // 保存房间代码映射
                await _redisService.SetAsync($"room_game:{roomCode}", gameId.ToString(), TimeSpan.FromHours(2));

                _logger.LogInformation("创建新游戏: GameId={GameId}, RoomCode={RoomCode}, Host={HostPlayerName}", 
                    gameId, roomCode, hostPlayerName);

                return new GameCreationResult
                {
                    Success = true,
                    GameId = gameId,
                    RoomCode = roomCode,
                    GameState = gameState,
                    HostPlayerId = hostPlayerId
                };
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, "创建游戏时发生错误: RoomCode={RoomCode}, HostPlayer={HostPlayerName}", 
                    roomCode, hostPlayerName);
                return new GameCreationResult
                {
                    Success = false,
                    Errors = { "创建游戏失败" }
                };
            }
        }

        /// <summary>
        /// 加入游戏
        /// </summary>
        public async Task<GameJoinResult> JoinGameAsync(string roomCode, Guid playerId, string playerName)
        {
            try
            {
                // 通过房间代码找到游戏ID
                var gameIdStr = await _redisService.GetAsync<string>($"room_game:{roomCode}");
                if (string.IsNullOrEmpty(gameIdStr) || !Guid.TryParse(gameIdStr, out var gameId))
                {
                    return new GameJoinResult
                    {
                        Success = false,
                        Errors = { "房间不存在或已过期" }
                    };
                }

                var gameState = await GetGameStateAsync(gameId);
                if (gameState == null)
                {
                    return new GameJoinResult
                    {
                        Success = false,
                        Errors = { "游戏状态无效" }
                    };
                }

                // 检查游戏状态
                if (gameState.Status == "finished")
                {
                    return new GameJoinResult
                    {
                        Success = false,
                        Errors = { "游戏已结束" }
                    };
                }

                if (gameState.Status == "playing")
                {
                    return new GameJoinResult
                    {
                        Success = false,
                        Errors = { "游戏进行中，无法加入" }
                    };
                }

                // 检查是否已在游戏中
                var existingPlayer = gameState.Players.FirstOrDefault(p => p.PlayerId == playerId);
                if (existingPlayer != null)
                {
                    return new GameJoinResult
                    {
                        Success = true,
                        GameId = gameId,
                        GameState = gameState,
                        PlayerState = existingPlayer,
                        IsRejoining = true
                    };
                }

                // 检查人数限制
                if (gameState.Players.Count >= gameState.MaxPlayers)
                {
                    return new GameJoinResult
                    {
                        Success = false,
                        Errors = { "游戏人数已满" }
                    };
                }

                // 创建新玩家
                var newPlayer = CreatePlayerState(playerId, playerName, gameState, isHost: false);
                gameState.Players.Add(newPlayer);

                // 保存状态
                await SaveGameStateAsync(gameId, gameState);

                _logger.LogInformation("玩家加入游戏: GameId={GameId}, PlayerId={PlayerId}, PlayerName={PlayerName}", 
                    gameId, playerId, playerName);

                return new GameJoinResult
                {
                    Success = true,
                    GameId = gameId,
                    GameState = gameState,
                    PlayerState = newPlayer,
                    IsRejoining = false
                };
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, "加入游戏时发生错误: RoomCode={RoomCode}, PlayerId={PlayerId}", roomCode, playerId);
                return new GameJoinResult
                {
                    Success = false,
                    Errors = { "加入游戏失败" }
                };
            }
        }

        /// <summary>
        /// 开始游戏
        /// </summary>
        public async Task<GameStartResult> StartGameAsync(Guid gameId, Guid hostPlayerId)
        {
            try
            {
                var gameState = await GetGameStateAsync(gameId);
                if (gameState == null)
                {
                    return new GameStartResult
                    {
                        Success = false,
                        Errors = { "游戏不存在" }
                    };
                }

                // 验证是否是房主
                var hostPlayer = gameState.Players.FirstOrDefault(p => p.PlayerId == hostPlayerId && p.IsHost);
                if (hostPlayer == null)
                {
                    return new GameStartResult
                    {
                        Success = false,
                        Errors = { "只有房主可以开始游戏" }
                    };
                }

                // 检查人数
                if (gameState.Players.Count < 2)
                {
                    return new GameStartResult
                    {
                        Success = false,
                        Errors = { "至少需要2名玩家才能开始游戏" }
                    };
                }

                // 检查游戏状态
                if (gameState.Status != "waiting")
                {
                    return new GameStartResult
                    {
                        Success = false,
                        Errors = { "游戏状态无效" }
                    };
                }

                // 开始游戏
                _logger.LogInformation("=== 开始游戏 === GameId: {GameId}, HostPlayerId: {HostPlayerId}", gameId, hostPlayerId);
                gameState.Status = "playing";
                gameState.StartTime = DateTime.UtcNow;
                gameState.EndTime = gameState.StartTime.Value.AddSeconds(gameState.Duration);
                
                _logger.LogInformation("游戏状态更新 - Status: {Status}, StartTime: {StartTime}, EndTime: {EndTime}", 
                    gameState.Status, gameState.StartTime, gameState.EndTime);
                
                // 初始化所有玩家状态
                _logger.LogInformation("初始化所有玩家状态，当前玩家数量: {PlayerCount}", gameState.Players.Count);
                foreach (var player in gameState.Players)
                {
                    _logger.LogInformation("初始化前玩家状态 - PlayerId: {PlayerId}, Username: {Username}, IsAlive: {IsAlive}", 
                        player.PlayerId, player.Username, player.IsAlive);
                        
                    player.IsAlive = true;
                    player.CurrentPosition = player.SpawnPoint;
                    player.IsDrawing = false;
                    player.CurrentPath.Clear();
                    player.RespawnTimestamp = DateTime.UtcNow.ToBinary();
                    
                    _logger.LogInformation("初始化后玩家状态 - PlayerId: {PlayerId}, Username: {Username}, IsAlive: {IsAlive}", 
                        player.PlayerId, player.Username, player.IsAlive);
                }

                // 生成道具（如果启用）
                if (gameState.EnablePowerUps)
                {
                    await GenerateInitialPowerUps(gameState);
                }

                await SaveGameStateAsync(gameId, gameState);

                _logger.LogInformation("游戏开始: GameId={GameId}, PlayerCount={PlayerCount}", gameId, gameState.Players.Count);

                return new GameStartResult
                {
                    Success = true,
                    GameId = gameId,
                    GameState = gameState,
                    StartTime = gameState.StartTime.Value,
                    Duration = gameState.Duration
                };
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, "开始游戏时发生错误: GameId={GameId}, HostPlayerId={HostPlayerId}", gameId, hostPlayerId);
                return new GameStartResult
                {
                    Success = false,
                    Errors = { "开始游戏失败" }
                };
            }
        }

        /// <summary>
        /// 离开游戏
        /// </summary>
        public async Task<GameLeaveResult> LeaveGameAsync(Guid gameId, Guid playerId)
        {
            try
            {
                var gameState = await GetGameStateAsync(gameId);
                if (gameState == null)
                {
                    return new GameLeaveResult { Success = true }; // 游戏不存在，视为成功离开
                }

                var player = gameState.Players.FirstOrDefault(p => p.PlayerId == playerId);
                if (player == null)
                {
                    return new GameLeaveResult { Success = true }; // 玩家不在游戏中，视为成功离开
                }

                // 移除玩家
                gameState.Players.RemoveAll(p => p.PlayerId == playerId);

                // 如果是房主离开且游戏未开始，转移房主权限
                if (player.IsHost && gameState.Status == "waiting" && gameState.Players.Count > 0)
                {
                    gameState.Players[0].IsHost = true;
                    _logger.LogInformation("房主离开，转移房主权限: GameId={GameId}, NewHost={NewHostId}", 
                        gameId, gameState.Players[0].PlayerId);
                }

                // 如果没有玩家了，标记游戏结束
                if (gameState.Players.Count == 0)
                {
                    gameState.Status = "finished";
                    gameState.EndTime = DateTime.UtcNow;
                }
                // 如果游戏进行中且只剩一个玩家，结束游戏
                else if (gameState.Status == "playing" && gameState.Players.Count(p => p.IsAlive) <= 1)
                {
                    gameState.Status = "finished";
                    gameState.EndTime = DateTime.UtcNow;
                    await UpdatePlayerRankings(gameState);
                }

                await SaveGameStateAsync(gameId, gameState);

                _logger.LogInformation("玩家离开游戏: GameId={GameId}, PlayerId={PlayerId}", gameId, playerId);

                return new GameLeaveResult
                {
                    Success = true,
                    RemainingPlayerCount = gameState.Players.Count
                };
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, "离开游戏时发生错误: GameId={GameId}, PlayerId={PlayerId}", gameId, playerId);
                return new GameLeaveResult
                {
                    Success = false,
                    Errors = { "离开游戏失败" }
                };
            }
        }

        // 私有辅助方法

        private bool ValidateActionRate(Guid playerId, long timestamp)
        {
            var key = $"action_rate:{playerId}";
            if (_lastActionTime.TryGetValue(key, out var lastTime))
            {
                var elapsed = DateTime.FromBinary(timestamp) - lastTime;
                if (elapsed.TotalMilliseconds < MIN_ACTION_INTERVAL_MS)
                {
                    return false;
                }
            }
            
            _lastActionTime[key] = DateTime.FromBinary(timestamp);
            return true;
        }

        /// <summary>
        /// 验证圆形地图移动合法性
        /// </summary>
        private async Task<MoveValidationResult> ValidateCircularMapMovement(Guid gameId, Guid playerId, Position newPosition)
        {
            var gameState = await GetGameStateAsync(gameId);
            if (gameState == null)
            {
                return new MoveValidationResult { IsValid = false, ErrorMessage = "游戏状态无效" };
            }

            // 圆形地图边界检查
            var centerX = gameState.MapWidth / 2.0;
            var centerY = gameState.MapHeight / 2.0;
            var mapRadius = Math.Min(gameState.MapWidth, gameState.MapHeight) / 2.0 - 10; // 留10像素边距
            
            var distanceFromCenter = Math.Sqrt(
                Math.Pow(newPosition.X - centerX, 2) + 
                Math.Pow(newPosition.Y - centerY, 2)
            );

            if (distanceFromCenter > mapRadius)
            {
                return new MoveValidationResult 
                { 
                    IsValid = false, 
                    ErrorMessage = "移动位置超出地图边界" 
                };
            }

            return new MoveValidationResult { IsValid = true };
        }

        /// <summary>
        /// 检查轨迹碰撞 - 实现精确的线段相交检测
        /// </summary>
        private async Task<DTOs.Game.CollisionResult> CheckTrailCollisionAsync(Guid gameId, Guid playerId, Position fromPos, Position toPos)
        {
            var gameState = await GetGameStateAsync(gameId);
            if (gameState == null)
            {
                return new DTOs.Game.CollisionResult();
            }

            var result = new DTOs.Game.CollisionResult();
            
            // 检查与其他玩家轨迹的碰撞
            foreach (var otherPlayer in gameState.Players.Where(p => p.PlayerId != playerId && p.IsDrawing))
            {
                if (otherPlayer.CurrentPath.Count < 2) continue;

                // 检查移动线段是否与其他玩家的轨迹相交
                for (int i = 0; i < otherPlayer.CurrentPath.Count - 1; i++)
                {
                    var trailStart = otherPlayer.CurrentPath[i];
                    var trailEnd = otherPlayer.CurrentPath[i + 1];
                    
                    if (DoLinesIntersect(fromPos, toPos, trailStart, trailEnd))
                    {
                        result.HasCollision = true;
                        result.CollidedWithPlayerId = otherPlayer.PlayerId;
                        result.CollisionType = "player_trail";
                        result.CollisionPoint = GetLineIntersection(fromPos, toPos, trailStart, trailEnd);
                        return result;
                    }
                }
            }

            // 检查自撞（与自己之前的轨迹碰撞）
            var currentPlayer = gameState.Players.First(p => p.PlayerId == playerId);
            if (currentPlayer.CurrentPath.Count > 3) // 至少需要4个点才可能自撞
            {
                // 只检查与前面的轨迹段（不包括最近的2段，避免与自己刚走过的路径冲突）
                for (int i = 0; i < currentPlayer.CurrentPath.Count - 3; i++)
                {
                    var trailStart = currentPlayer.CurrentPath[i];
                    var trailEnd = currentPlayer.CurrentPath[i + 1];
                    
                    if (DoLinesIntersect(fromPos, toPos, trailStart, trailEnd))
                    {
                        result.HasCollision = true;
                        result.CollisionType = "self_trail";
                        result.CollisionPoint = GetLineIntersection(fromPos, toPos, trailStart, trailEnd);
                        return result;
                    }
                }
            }

            return result;
        }

        /// <summary>
        /// 检查两条线段是否相交
        /// </summary>
        private bool DoLinesIntersect(Position p1, Position q1, Position p2, Position q2)
        {
            int o1 = GetOrientation(p1, q1, p2);
            int o2 = GetOrientation(p1, q1, q2);
            int o3 = GetOrientation(p2, q2, p1);
            int o4 = GetOrientation(p2, q2, q1);

            // 一般情况
            if (o1 != o2 && o3 != o4)
                return true;

            // 特殊情况：点共线且重叠
            if (o1 == 0 && OnSegment(p1, p2, q1)) return true;
            if (o2 == 0 && OnSegment(p1, q2, q1)) return true;
            if (o3 == 0 && OnSegment(p2, p1, q2)) return true;
            if (o4 == 0 && OnSegment(p2, q1, q2)) return true;

            return false;
        }

        private int GetOrientation(Position p, Position q, Position r)
        {
            double val = (q.Y - p.Y) * (r.X - q.X) - (q.X - p.X) * (r.Y - q.Y);
            if (Math.Abs(val) < 1e-10) return 0; // 共线
            return val > 0 ? 1 : 2; // 顺时针或逆时针
        }

        private bool OnSegment(Position p, Position q, Position r)
        {
            return q.X <= Math.Max(p.X, r.X) && q.X >= Math.Min(p.X, r.X) &&
                   q.Y <= Math.Max(p.Y, r.Y) && q.Y >= Math.Min(p.Y, r.Y);
        }

        private Position? GetLineIntersection(Position p1, Position q1, Position p2, Position q2)
        {
            double a1 = q1.Y - p1.Y;
            double b1 = p1.X - q1.X;
            double c1 = a1 * p1.X + b1 * p1.Y;

            double a2 = q2.Y - p2.Y;
            double b2 = p2.X - q2.X;
            double c2 = a2 * p2.X + b2 * p2.Y;

            double determinant = a1 * b2 - a2 * b1;
            if (Math.Abs(determinant) < 1e-10)
                return null; // 平行线

            double x = (b2 * c1 - b1 * c2) / determinant;
            double y = (a1 * c2 - a2 * c1) / determinant;
            return new Position((float)x, (float)y);
        }

        /// <summary>
        /// 检查玩家领地状态
        /// </summary>
        private TerritoryStatusInfo CheckPlayerTerritoryStatus(LineDrawingPlayerState player, Position position, List<LineDrawingPlayerState> allPlayers)
        {
            var info = new TerritoryStatusInfo();
            
            // 检查是否在安全区域（出生点50像素范围内）
            if (position.IsWithinRadius(player.SpawnPoint, 50))
            {
                info.IsInSafeZone = true;
                info.IsInOwnTerritory = true;
                return info;
            }

            // 检查是否在己方领地内
            foreach (var territory in player.Territories)
            {
                if (territory.Contains(position))
                {
                    info.IsInOwnTerritory = true;
                    return info;
                }
            }

            // 检查是否在其他玩家领地内
            foreach (var otherPlayer in allPlayers.Where(p => p.PlayerId != player.PlayerId))
            {
                foreach (var territory in otherPlayer.Territories)
                {
                    if (territory.Contains(position))
                    {
                        info.IsInEnemyTerritory = true;
                        info.EnemyTerritoryOwner = otherPlayer.PlayerId;
                        return info;
                    }
                }
            }

            // 在中立区域
            info.IsInNeutralZone = true;
            return info;
        }

        /// <summary>
        /// 更新威胁检测 - 实现轨迹预警系统
        /// </summary>
        private Task UpdateThreatDetection(LineDrawingPlayerState player, List<LineDrawingPlayerState> allPlayers)
        {
            if (!player.IsDrawing || player.CurrentPath.Count < 2)
            {
                player.IsUnderThreat = false;
                player.ThreatSourcePlayerId = null;
                return Task.CompletedTask;
            }

            const double THREAT_DISTANCE = 3.0; // 3像素内视为威胁

            foreach (var otherPlayer in allPlayers.Where(p => p.PlayerId != player.PlayerId && p.IsAlive))
            {
                // 检查其他玩家是否接近当前玩家的轨迹
                foreach (var pathPoint in player.CurrentPath)
                {
                    var distance = otherPlayer.CurrentPosition.DistanceTo(pathPoint);
                    if (distance <= THREAT_DISTANCE)
                    {
                        player.IsUnderThreat = true;
                        player.ThreatSourcePlayerId = otherPlayer.PlayerId;
                        return Task.CompletedTask;
                    }
                }
            }

            player.IsUnderThreat = false;
            player.ThreatSourcePlayerId = null;
            return Task.CompletedTask;
        }

        /// <summary>
        /// 计算有效移动速度 - 根据领地状态调整
        /// </summary>
        private double CalculateEffectiveMovementSpeed(LineDrawingPlayerState player, TerritoryStatusInfo territoryInfo)
        {
            var baseSpeed = player.MovementSpeed;
            
            // 在己方领地内速度提升15%
            if (territoryInfo.IsInOwnTerritory)
            {
                baseSpeed *= 1.15;
            }
            // 在敌方领地内速度降低20%
            else if (territoryInfo.IsInEnemyTerritory)
            {
                baseSpeed *= 0.80;
            }

            // 护盾激活时移动速度降低10%
            if (player.HasShield)
            {
                baseSpeed *= 0.90;
            }

            return baseSpeed;
        }

        /// <summary>
        /// 检查是否可以在指定位置开始画线
        /// </summary>
        private bool CanStartDrawingAt(LineDrawingPlayerState player, Position position, List<LineDrawingPlayerState> allPlayers)
        {
            var territoryInfo = CheckPlayerTerritoryStatus(player, position, allPlayers);
            
            // 只能从己方领地或安全区域开始画线
            return territoryInfo.IsInOwnTerritory || territoryInfo.IsInSafeZone;
        }

        /// <summary>
        /// 创建玩家状态 - 实现出生点系统
        /// 根据游戏规则：每位玩家在地图边缘有专属出生点，颜色与玩家标识一致
        /// 出生点周围有固定大小的安全区域（半径50像素的圆形初始领地）
        /// </summary>
        private LineDrawingPlayerState CreatePlayerState(Guid playerId, string playerName, LineDrawingGameState gameState, bool isHost)
        {
            _logger.LogInformation("=== 创建玩家状态开始 === PlayerId: {PlayerId}, PlayerName: {PlayerName}, IsHost: {IsHost}", 
                playerId, playerName, isHost);
            
            // 预定义的玩家颜色 - 与玩家标识一致
            var colors = new[]
            {
                "#FF6B6B", "#4ECDC4", "#45B7D1", "#96CEB4",
                "#FFEAA7", "#DDA0DD", "#98D8C8", "#F7DC6F"
            };

            // 分配颜色
            var colorIndex = gameState.Players.Count % colors.Length;
            var playerColor = colors[colorIndex];

            // 出生点系统：在地图边缘均匀分布
            // 圆形地图边界上的出生点计算
            var centerX = gameState.MapWidth / 2.0;
            var centerY = gameState.MapHeight / 2.0;
            var mapRadius = Math.Min(gameState.MapWidth, gameState.MapHeight) / 2.0;
            
            // 出生点在地图边缘，留出安全距离
            var spawnRadius = mapRadius - 80; // 留出80像素边距，确保安全区域完全在地图内
            
            // 根据当前玩家数量均匀分布出生点
            var totalPlayers = Math.Max(gameState.MaxPlayers, 8); // 至少按8个玩家分布
            var angleStep = 2 * Math.PI / totalPlayers;
            var angle = gameState.Players.Count * angleStep;
            
            var spawnX = centerX + spawnRadius * Math.Cos(angle);
            var spawnY = centerY + spawnRadius * Math.Sin(angle);
            var spawnPoint = new Position((float)spawnX, (float)spawnY);

            // 创建初始安全区域（半径50像素的圆形领地）
            // 根据游戏规则：出生点周围有固定大小的安全区域
            var initialTerritory = CreateCircularTerritory(spawnPoint, 50);
            var initialArea = Math.PI * 50 * 50;

            var newPlayer = new LineDrawingPlayerState
            {
                PlayerId = playerId,
                Username = playerName,
                Color = playerColor,
                IsHost = isHost,
                CurrentPosition = spawnPoint,
                SpawnPoint = spawnPoint,
                IsAlive = true,
                IsDrawing = false,
                CurrentPath = new List<Position>(),
                Territories = new List<Territory> { initialTerritory },
                TotalTerritoryArea = initialArea,
                MaxTerritoryArea = initialArea,
                MovementSpeed = 1.0,
                KillCount = 0,
                DeathCount = 0,
                Rank = gameState.Players.Count + 1,
                // 复活相关字段初始化
                ConsecutiveDeaths = 0,
                LastDeathTime = null,
                InvincibilityEndTime = null
            };
            
            _logger.LogInformation("=== 玩家状态创建完成 === PlayerId: {PlayerId}, Username: {Username}, IsAlive: {IsAlive}, Color: {Color}, SpawnPoint: {SpawnPoint}", 
                newPlayer.PlayerId, newPlayer.Username, newPlayer.IsAlive, newPlayer.Color, newPlayer.SpawnPoint);
                
            return newPlayer;
        }

        /// <summary>
        /// 创建圆形领地
        /// </summary>
        private Territory CreateCircularTerritory(Position center, int radius)
        {
            var points = new List<Position>();
            var pointCount = 16; // 16个点组成圆形

            for (int i = 0; i < pointCount; i++)
            {
                var angle = 2 * Math.PI * i / pointCount;
                var x = center.X + radius * Math.Cos(angle);
                var y = center.Y + radius * Math.Sin(angle);
                points.Add(new Position((float)x, (float)y));
            }

            return new Territory(points);
        }

        private Task GenerateInitialPowerUps(LineDrawingGameState gameState)
        {
            // 初始道具数量基于地图大小和玩家数量
            var powerUpCount = Math.Max(4, gameState.Players.Count * 2);
            var random = new Random();
            
            for (int i = 0; i < powerUpCount; i++)
            {
                // 在地图中随机位置生成道具
                var centerX = gameState.MapWidth / 2.0;
                var centerY = gameState.MapHeight / 2.0;
                var maxRadius = Math.Min(gameState.MapWidth, gameState.MapHeight) / 2.0 * 0.8; // 80%半径内

                var angle = random.NextDouble() * 2 * Math.PI;
                var distance = random.NextDouble() * maxRadius;
                
                var x = centerX + distance * Math.Cos(angle);
                var y = centerY + distance * Math.Sin(angle);

                // 随机选择道具类型
                var powerUpTypes = Enum.GetValues<PowerUpType>();
                var randomType = powerUpTypes[random.Next(powerUpTypes.Length)];

                var powerUp = new PowerUpState
                {
                    Id = Guid.NewGuid(),
                    Type = randomType,
                    Position = new Position((float)x, (float)y),
                    CreatedAt = DateTime.UtcNow,
                    IsCollected = false
                };

                gameState.PowerUps.Add(powerUp);
            }

            return Task.CompletedTask;
        }

        private double CalculatePathLength(List<Position> path)
        {
            if (path.Count < 2) return 0;
            
            double length = 0;
            for (int i = 1; i < path.Count; i++)
            {
                length += path[i-1].DistanceTo(path[i]);
            }
            return length;
        }

        private bool IsInOwnTerritoryOrNeutral(LineDrawingPlayerState player, Position position)
        {
            // 检查是否在己方领地或出生点安全区域
            if (position.IsWithinRadius(player.SpawnPoint, 50)) // 50像素安全区域
                return true;
                
            return player.Territories.Any(t => t.Contains(position));
        }

        private bool CanStartDrawingAt(LineDrawingPlayerState player, Position position)
        {
            return IsInOwnTerritoryOrNeutral(player, position);
        }

        /// <summary>
        /// 检查是否可以在指定位置完成画线
        /// </summary>
        private bool CanCompleteDrawingAt(LineDrawingPlayerState player, Position position, List<LineDrawingPlayerState> allPlayers)
        {
            if (player.CurrentPath.Count == 0) return false;
            
            var territoryInfo = CheckPlayerTerritoryStatus(player, position, allPlayers);
            
            // 可以在己方领地边缘完成，或者回到起点附近
            var startPoint = player.CurrentPath[0];
            if (position.DistanceTo(startPoint) <= 15) // 15像素容差
                return true;
                
            // 也可以在己方领地或安全区域完成
            return territoryInfo.IsInOwnTerritory || territoryInfo.IsInSafeZone;
        }

        private Task UpdatePlayerRankings(LineDrawingGameState gameState)
        {
            var rankedPlayers = gameState.Players
                .OrderByDescending(p => p.TotalTerritoryArea)
                .ToList();
                
            for (int i = 0; i < rankedPlayers.Count; i++)
            {
                rankedPlayers[i].Rank = i + 1;
            }

            return Task.CompletedTask;
        }

        private double CalculateAreaPercentage(double playerArea, int mapWidth, int mapHeight)
        {
            var totalArea = Math.PI * Math.Pow(Math.Min(mapWidth, mapHeight) / 2.0, 2); // 圆形地图面积
            return (playerArea / totalArea) * 100.0;
        }

        private async Task SaveGameStateAsync(Guid gameId, LineDrawingGameState gameState)
        {
            try
            {
                _logger.LogInformation("=== 开始保存游戏状态 === GameId: {GameId}, Status: {Status}, PlayerCount: {PlayerCount}", 
                    gameId, gameState.Status, gameState.Players.Count);
                
                var stateJson = JsonSerializer.Serialize(gameState);
                _logger.LogDebug("序列化游戏状态完成，JSON长度: {JsonLength}", stateJson.Length);
                
                await _redisService.SetAsync($"game_state:{gameId}", stateJson, TimeSpan.FromHours(1));
                _logger.LogInformation("游戏状态已保存到Redis: game_state:{GameId}", gameId);
                
                _gameStates.AddOrUpdate(gameId, gameState, (key, oldValue) => gameState);
                _logger.LogInformation("游戏状态已更新到内存缓存: {GameId}", gameId);
                
                _logger.LogInformation("=== 游戏状态保存完成 === GameId: {GameId}", gameId);
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, "保存游戏状态时发生错误: GameId={GameId}", gameId);
            }
        }

        /// <summary>
        /// 获取游戏排行榜
        /// </summary>
        /// <param name="gameId">游戏ID</param>
        /// <returns>玩家排行榜</returns>
        public async Task<List<PlayerScoreDto>> GetLeaderboardAsync(Guid gameId)
        {
            try
            {
                var gameState = await GetGameStateAsync(gameId);
                if (gameState == null)
                {
                    return new List<PlayerScoreDto>();
                }

                return gameState.Players
                    .OrderByDescending(p => p.TotalTerritoryArea)
                    .Select(p => new PlayerScoreDto
                    {
                        PlayerId = p.PlayerId,
                        PlayerName = p.Username,
                        Score = (int)p.TotalTerritoryArea
                    })
                    .ToList();
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, "获取游戏排行榜时发生错误: GameId={GameId}", gameId);
                return new List<PlayerScoreDto>();
            }
        }

        /// <summary>
        /// 玩家复活
        /// </summary>
        public async Task<PlayerRespawnResult> RespawnPlayerAsync(Guid gameId, Guid playerId)
        {
            try
            {
                var gameState = await GetGameStateAsync(gameId);
                if (gameState == null)
                {
                    return new PlayerRespawnResult
                    {
                        Success = false,
                        Errors = new List<string> { "游戏不存在" }
                    };
                }

                var player = gameState.Players.FirstOrDefault(p => p.PlayerId == playerId);
                if (player == null)
                {
                    return new PlayerRespawnResult
                    {
                        Success = false,
                        Errors = new List<string> { "玩家不存在" }
                    };
                }

                // 检查玩家是否已经存活
                if (player.IsAlive)
                {
                    return new PlayerRespawnResult
                    {
                        Success = false,
                        Errors = new List<string> { "玩家已经存活" }
                    };
                }

                // 生成复活位置（地图中心附近的随机位置）
                var random = new Random();
                var centerX = gameState.MapWidth / 2.0;
                var centerY = gameState.MapHeight / 2.0;
                var mapRadius = Math.Min(gameState.MapWidth, gameState.MapHeight) / 2.0;
                
                var respawnPosition = new Position(
                    (float)(centerX + (random.NextDouble() - 0.5) * 200),
                    (float)(centerY + (random.NextDouble() - 0.5) * 200)
                );

                // 确保复活位置在地图边界内
                var distance = Math.Sqrt(Math.Pow(respawnPosition.X - centerX, 2) + 
                                        Math.Pow(respawnPosition.Y - centerY, 2));
                if (distance > mapRadius - 50)
                {
                    var angle = Math.Atan2(respawnPosition.Y - centerY, respawnPosition.X - centerX);
                    var safeDistance = mapRadius - 50;
                    respawnPosition = new Position(
                        (float)(centerX + safeDistance * Math.Cos(angle)),
                        (float)(centerY + safeDistance * Math.Sin(angle))
                    );
                }

                // 复活玩家
                player.IsAlive = true;
                player.CurrentPosition = respawnPosition;
                player.SpawnPoint = respawnPosition;
                player.IsDrawing = false;
                player.CurrentPath.Clear();
                player.HasShield = false;
                player.IsGhost = false;
                player.MovementSpeed = BASE_MOVEMENT_SPEED;

                // 保存游戏状态
                await SaveGameStateAsync(gameId, gameState);

                _logger.LogInformation("玩家复活成功: PlayerId={PlayerId}, GameId={GameId}, Position=({X},{Y})", 
                    playerId, gameId, respawnPosition.X, respawnPosition.Y);

                return new PlayerRespawnResult
                {
                    Success = true,
                    SpawnPosition = respawnPosition,
                    IsInvincible = true,
                    InvincibilityTimeMs = 5000,
                    Timestamp = DateTimeOffset.UtcNow.ToUnixTimeMilliseconds()
                };
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, "玩家复活失败: PlayerId={PlayerId}, GameId={GameId}", playerId, gameId);
                return new PlayerRespawnResult
                {
                    Success = false,
                    Errors = new List<string> { "复活失败，请稍后重试" }
                };
            }
        }

        // 道具相关辅助方法

        private int GetPowerUpDuration(PowerUpType powerUpType)
        {
            return powerUpType switch
            {
                PowerUpType.Lightning => 8,
                PowerUpType.Shield => 12,
                PowerUpType.Ghost => 10,
                PowerUpType.Bomb => 0, // 瞬间效果
                _ => 10
            };
        }

        private string GetPowerUpName(PowerUpType powerUpType)
        {
            return powerUpType switch
            {
                PowerUpType.Lightning => "闪电",
                PowerUpType.Shield => "护盾",
                PowerUpType.Ghost => "幽灵",
                PowerUpType.Bomb => "炸弹",
                _ => "未知"
            };
        }

        private string GetPowerUpDescription(PowerUpType powerUpType)
        {
            return powerUpType switch
            {
                PowerUpType.Lightning => "移动速度提升60%，持续8秒",
                PowerUpType.Shield => "免疫一次截断攻击，持续12秒",
                PowerUpType.Ghost => "穿越敌方轨迹不死亡，持续10秒",
                PowerUpType.Bomb => "在当前位置创造领地，半径30像素",
                _ => "未知道具"
            };
        }
    }
}